package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

func postForm() {
	// form data 形似 query string，类似于 name=lcl&age=21
	data := make(url.Values)
	data.Add("name", "lcl")
	data.Add("age", "21")
	payload := data.Encode()

	r, _ := http.Post(
		"http://httpbin.org/post",
		"application/x-www-form-urlencoded",
		strings.NewReader(payload),
	)
	defer func() { _ = r.Body.Close() }()

	content, _ := ioutil.ReadAll(r.Body)
	fmt.Printf("%s", content)
}

func postJson() {
	u := struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}{
		Name: "lcl",
		Age:  21,
	}
	payload, _ := json.Marshal(u)

	r, _ := http.Post(
		"http://httpbin.org/post",
		"application/json",
		bytes.NewReader(payload),
	)
	defer func() { _ = r.Body.Close() }()

	content, _ := ioutil.ReadAll(r.Body)
	fmt.Printf("%s", content)
}

func main() {
	// post 请求，是通过request body提交，相对get请求（urlencoded，提交查询参数，提交内容有大小限制，好像是2kb）
	// post的不同形式，也是就body的形式不同
	// post json，提交json格式
	// post form，body的形式就是urlencoded的形式，比如name=lcl&age=21
	// post 文件
	//postForm()
	postJson()
}

